# 第 0017 题： 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中，下所示：

import json
import xml.etree.ElementTree
from xml.dom import minidom

from openpyxl import load_workbook


# class RawText(minidom.Text):
#     def writexml(self, writer, indent="", addindent="", newl=""):
#         data1 = "%s%s%s" % (indent, self.data, newl)
#         if data1:
#             writer.write(data1)


def student_excel(xlsx):
    wb = load_workbook(xlsx)
    ws = wb['student']

    student_dict = {}
    for i, r in enumerate(ws.rows):
        student_list = []
        for j, c in enumerate(r):
            if j > 0:
                student_list.append(c.value)
            else:
                student_dict[c.value] = student_list

    # return json.dumps(student_dict, indent=4, ensure_ascii=False, sort_keys=False, separators=(',', ':'))
    return str(student_dict)


def student_xml(filepath, data):
    doc = xml.dom.minidom.Document()
    root = doc.createElement('root')
    doc.appendChild(root)
    students = doc.createElement('students')
    # textNode = RawText()
    # textNode.data =data
    students.appendChild(doc.createComment('学生信息表 "id" : [名字, 数学, 语文, 英文]'))
    students.appendChild(doc.createTextNode(data))
    root.appendChild(students)
    file = open(filepath, 'w', encoding="utf-8")
    doc.writexml(file, indent='\t', addindent='\t', newl='\n', encoding="utf-8")


if __name__ == '__main__':
    data = student_excel(r'resource/xml/student.xlsx')
    print(data)
    student_xml(r'resource/xml/student.xml', data)
